import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import store from '@/store'

// 路由懒加载
const Login = () => import('@/views/login/index.vue')
const Register = () => import('@/views/register/index.vue')
const TeacherDashboard = () => import('@/views/teacher/dashboard/index.vue')
const StudentDashboard = () => import('@/views/student/dashboard/index.vue')

const routes = [
  {
    path: '/',
    redirect: () => {
      const token = store.state.token
      if (!token) return '/login'
      
      const role = store.state.user?.role
      switch (role) {
        case 'ADMIN':
          return '/admin/dashboard'
        case 'TEACHER':
          return '/teacher/dashboard'
        case 'STUDENT':
          return '/student/dashboard'
        default:
          return '/login'
      }
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', noAuth: true },
    hidden: true
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { title: '注册', noAuth: true },
    hidden: true
  },
  {
    path: '/admin',
    component: Layout,
    meta: { roles: ['ADMIN'] },
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/admin/dashboard/index.vue'),
        meta: { title: '控制台' }
      },
      {
        path: 'users',
        component: () => import('@/views/admin/users/index.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'announcements',
        component: () => import('@/views/admin/announcements/index.vue'),
        meta: { title: '公告管理' }
      },
      {
        path: 'job-categories',
        component: () => import('@/views/admin/job-categories/JobCategoryList.vue'),
        meta: { title: '岗位分类' }
      },
      {
        path: 'positions',
        component: () => import('@/views/admin/positions/JobPositionList.vue'),
        meta: { title: '岗位列表' }
      },
      {
        path: 'applications',
        name: 'AdminApplications',
        component: () => import('@/views/admin/applications/JobApplicationList.vue'),
        meta: { title: '岗位申请管理', icon: 'document' }
      },
      {
        path: 'employees',
        name: 'AdminEmployees',
        component: () => import('@/views/admin/employees/EmployeeList.vue'),
        meta: { title: '在岗人员', icon: 'user' }
      },
      {
        path: 'work-hours',
        component: () => import('@/views/admin/work-hours/WorkHoursStatList.vue'),
        meta: { title: '工时统计', icon: 'calendar' }
      },
      {
        path: 'work-records',
        name: 'AdminWorkRecords',
        component: () => import('@/views/admin/work-records/WorkRecordList.vue'),
        meta: { title: '工作记录', icon: 'document' }
      },
      {
        path: 'scholarships',
        component: () => import('@/views/admin/scholarships/ScholarshipList.vue'),
        meta: { title: '奖学金项目' }
      },
      {
        path: 'scholarship-applications',
        name: 'AdminScholarshipApplications',
        component: () => import('@/views/admin/scholarship-applications/ScholarshipApplicationList.vue'),
        meta: { title: '奖学金申请管理' }
      },
      {
        path: 'feedback',
        component: () => import('@/views/admin/feedback/index.vue'),
        meta: { title: '反馈管理' }
      },
      {
        path: 'student-accounts',
        name: 'AdminStudentAccounts',
        component: () => import('@/views/admin/student-accounts/StudentAccountList.vue'),
        meta: { title: '学生账户管理', icon: 'money' }
      },
      {
        path: 'profile',
        name: 'AdminProfile',
        component: () => import('@/views/admin/profile/index.vue'),
        meta: { title: '个人信息', icon: 'user' },
      },
    ]
  },
  {
    path: '/teacher',
    component: Layout,
    meta: { roles: ['TEACHER'] },
    children: [
      {
        path: 'dashboard',
        component: TeacherDashboard,
        meta: { title: '工作台' }
      },
      {
        path: 'positions',
        name: 'TeacherPositions',
        component: () => import('@/views/teacher/positions/JobPositionList.vue'),
        meta: { title: '岗位管理', icon: 'work' }
      },
      {
        path: 'applications',
        name: 'TeacherApplications',
        component: () => import('@/views/teacher/applications/JobApplicationList.vue'),
        meta: { title: '岗位申请管理', icon: 'document' }
      },
      {
        path: 'employees',
        name: 'TeacherEmployees',
        component: () => import('@/views/teacher/employees/EmployeeList.vue'),
        meta: { title: '在岗人员', icon: 'user' }
      },
      {
        path: 'work-records',
        name: 'TeacherWorkRecords',
        component: () => import('@/views/teacher/work-records/WorkRecordList.vue'),
        meta: { title: '工作记录', icon: 'document' }
      },
      {
        path: 'work-hours',
        name: 'TeacherWorkHours',
        component: () => import('@/views/teacher/work-hours/WorkHoursStatList.vue'),
        meta: { title: '工时统计', icon: 'calendar' }
      },
      {
        path: 'scholarship-applications',
        name: 'TeacherScholarshipApplications',
        component: () => import('@/views/teacher/scholarship-applications/ScholarshipApplicationList.vue'),
        meta: { title: '奖学金审核', icon: 'money' }
      },
      {
        path: 'scholarships',
        name: 'TeacherScholarships',
        component: () => import('@/views/teacher/scholarships/ScholarshipList.vue'),
        meta: { title: '奖学金管理', icon: 'money' }
      },
      {
        path: 'feedback',
        name: 'TeacherFeedback',
        component: () => import('@/views/teacher/feedback/FeedbackList.vue'),
        meta: { title: '反馈管理', icon: 'message' }
      },
      {
        path: 'profile',
        name: 'TeacherProfile',
        component: () => import('@/views/teacher/profile/index.vue'),
        meta: { title: '个人信息', icon: 'user' }
      }
    ]
  },
  {
    path: '/student',
    component: Layout,
    meta: { roles: ['STUDENT'] },
    children: [
      {
        path: 'dashboard',
        component: StudentDashboard,
        meta: { title: '工作台' }
      },
      {
        path: 'positions',
        name: 'StudentPositions',
        component: () => import('@/views/student/positions/JobPositionList.vue'),
        meta: { title: '岗位申请', icon: 'work' }
      },
      {
        path: 'applications',
        component: () => import('@/views/student/applications/JobApplicationList.vue'),
        meta: { title: '我的申请' }
      },
      {
        path: 'work-hours',
        name: 'StudentWorkHours',
        component: () => import('@/views/student/records/WorkHoursStatList.vue'),
        meta: { title: '工时统计', icon: 'calendar' }
      },
      {
        path: 'scholarships',
        name: 'StudentScholarships',
        component: () => import('@/views/student/scholarships/ScholarshipList.vue'),
        meta: { title: '奖学金申请', icon: 'money' }
      },
      {
        path: 'scholarship-applications',
        name: 'StudentScholarshipApplications',
        component: () => import('@/views/student/scholarship-applications/ScholarshipApplicationList.vue'),
        meta: { title: '我的奖学金申请' }
      },
      {
        path: 'feedback',
        name: 'StudentFeedback',
        component: () => import('@/views/student/feedback/FeedbackList.vue'),
        meta: { title: '我的反馈', icon: 'message' }
      },
      {
        path: 'account',
        name: 'StudentAccount',
        component: () => import('@/views/student/account/AccountForm.vue'),
        meta: { title: '收款账户', icon: 'money' }
      },
      {
        path: 'profile',
        name: 'StudentProfile',
        component: () => import('@/views/student/profile/index.vue'),
        meta: { title: '个人信息', icon: 'user' }
      }
    ]
  },
  {
    path: '/profile',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人信息' }
      }
    ]
  },
  // 403 页面
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: { title: '403', noAuth: true }
  },
  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', noAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = store.state.token
  
  if (to.meta.noAuth) {
    next()
    return
  }

  if (!token) {
    next('/login')
    return
  }

  // 如果有 token 但没有用户信息，尝试重新获取用户信息
  if (!store.state.user) {
    try {
      await store.dispatch('getProfile')
    } catch (error) {
      store.commit('CLEAR_AUTH')
      next('/login')
      return
    }
  }

  const userRole = store.state.user?.role
  const allowedRoles = to.meta?.roles

  if (allowedRoles && !allowedRoles.includes(userRole)) {
    next('/403')
  } else {
    next()
  }
})

export default router 